package com.myslef.teaching_platfrom.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.myslef.teaching_platfrom.common.R;
import com.myslef.teaching_platfrom.domain.task.Task;
import com.myslef.teaching_platfrom.domain.users.User;
import com.myslef.teaching_platfrom.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/task")
@CrossOrigin(origins = "http://localhost:8080")
public class TaskController {
    @Autowired
    private TaskService taskService;

    @Value("${upload.dir}") // 读取配置文件中的上传文件保存目录
    private String uploadDir;

    @PostMapping
    public R creatTask(@RequestParam(required = false,value = "file") MultipartFile[] files,
                       @RequestParam(required = false,value = "content") String content,
                       @RequestParam("user")String strUser,
                       @RequestParam("classId")String classId,
                       @RequestParam("deadline")String deadline,
                       @RequestParam("taskName")String taskName) throws ParseException, IOException {
        if(taskName == "undefined" || taskName == ""){
            return R.error("请输入作业名");
        }
        if(deadline == "undefined" || deadline == ""){
            return R.error("截止时间未设置！");
        }

        User user = JSON.parseObject(strUser, User.class);

        Path uploadPath = Paths.get(uploadDir+"/task/"+System.currentTimeMillis()+classId);
        List<String> list = new ArrayList<>();
        if(files != null)
            for (int i = 0; i < files.length; i++) {
                String originalFileName = files[i].getOriginalFilename();
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
                if (!Files.exists(uploadPath)) {
                    try {
                        Files.createDirectories(uploadPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Path filePath = Paths.get(uploadPath.toString(), originalFileName);
                list.add(filePath.toString());
                Files.write(filePath, files[i].getBytes());

            }

        Task task = new Task();

        String str = String.join(",", list);
        task.setTaskUrlList(str);
        task.setContent(content);
        task.setTaskName(taskName);
        task.setCourseId(Integer.parseInt(classId));
        task.setTeacherId(user.getId());
        task.setSubmittedCount(0);
        String dateFormat = "yyyy-MM-dd HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        Date date = format.parse(deadline);
        Timestamp timestamp = new Timestamp(date.getTime());
        task.setDeadline(timestamp);
        task.setCreateTime(new Timestamp(System.currentTimeMillis()));
        boolean save = taskService.save(task);
        if(save)
            return R.success("添加成功！");
        else
            return R.error("添加失败");
    }

    @GetMapping("/{courseId}")
    public R getTaskList(@PathVariable Integer courseId){
        List<Task> taskList = taskService.getTaskList(courseId);
        if(taskList!=null)
            return R.success(taskList);
        else
            return R.error("获取列表失败！");
    }


    @DeleteMapping("/{taskId}")
    public R deleteTask(@PathVariable Integer taskId){
        boolean removeById = taskService.removeById(taskId);
        if(removeById)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }
    @PutMapping
    public R updateTask(@RequestParam(required = false,value = "file") MultipartFile[] files,
                       @RequestParam(required = false,value = "content") String content,
                       @RequestParam("taskId")String taskId,
                       @RequestParam("deadline")String deadline,
                       @RequestParam("taskName")String taskName) throws ParseException, IOException {
        if(taskName == "undefined" || taskName == ""){
            return R.error("请输入作业名");
        }
        if(deadline == "undefined" || deadline == ""){
            return R.error("截止时间未设置！");
        }
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Task::getId).eq(Task::getId,taskId);
        Task task = taskService.getOne(queryWrapper);


        if(task == null){
            return R.error("未找到该任务");
        }

        Path uploadPath = Paths.get(uploadDir+"/task/"+System.currentTimeMillis()+taskId);
        List<String> list = new ArrayList<>();
        if(files != null)
            for (int i = 0; i < files.length; i++) {
                String originalFileName = files[i].getOriginalFilename();
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
                if (!Files.exists(uploadPath)) {
                    try {
                        Files.createDirectories(uploadPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Path filePath = Paths.get(uploadPath.toString(), originalFileName);
                list.add(filePath.toString());
                Files.write(filePath, files[i].getBytes());

            }


        String str = String.join(",", list);
//        task.setTaskUrlList(str);
//        task.setContent(content);
//        task.setTaskName(taskName);
//        task.setSubmittedCount(0);
        String dateFormat = "yyyy-MM-dd HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        Date date = format.parse(deadline);
        Timestamp timestamp = new Timestamp(date.getTime());
//        task.setDeadline(timestamp);

        LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Task::getId,task.getId()).set(Task::getTaskUrlList,str).set(Task::getContent,content)
                .set(Task::getTaskName,taskName).set(Task::getDeadline,timestamp);
        boolean save = taskService.update(updateWrapper);
        if(save)
            return R.success("修改成功！");
        else
            return R.error("修改失败！");
    }
}
